package org.cladwell;

import org.cladwell.constant.UserConstant;
import org.cladwell.domain.FollowingGroup;
import org.cladwell.domain.User;
import org.cladwell.domain.UserFollowing;
import org.cladwell.exception.ConditionException;
import org.cladwell.mapper.UserFollowingDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class UserFollowingService {
    @Autowired
    private UserFollowingDao userFollowingDao;
    @Autowired
    private FollowingGroupService followingGroupService;
    @Autowired
    private UserService userService;
    @Transactional
    public void addUserFollowing(UserFollowing userFollowing){
        Long groupid = userFollowing.getGroupid();
        if(groupid==null){
            FollowingGroup byType = followingGroupService.getByType(UserConstant.group_Default);
            userFollowing.setGroupid(byType.getId());
        }else {
            FollowingGroup byId = followingGroupService.getById(groupid);
            if(byId==null){
                throw new ConditionException("分组不存在");
            }
            Long followingid = userFollowing.getFollowingid();
            User userById = userService.getUserById(followingid);
            if(userById==null){
                throw new ConditionException("关注用户不存在");
            }
            userFollowingDao.delete(userFollowing.getUserid(),userFollowing.getFollowingid());
            userFollowing.setCreateTime(new Date());
            userFollowingDao.add(userFollowing);

        }
    }
}
